package com.smartthinking.CICPNL.home.activity;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.smartthinking.CICPNL.R;
import com.smartthinking.CICPNL.R.id;
import com.smartthinking.CICPNL.home.objects.App_ImageLoader;

public class Mensajes extends Activity {

	private ImageView imagen;
	private TextView titulo;
	private Dictionary dic;
	public ListView list;
	public ListAdapter adapter;
	public Dialog progressDialog;
	public App_ImageLoader imageLoader;
	private Intent intent;
	private boolean put_filter = false;
	private String put_qry;
	public static ArrayList<Dictionary> Actividades = null;
	public static ArrayList<Dictionary<String,String>> TraeDatos = null;
	public static ArrayList<Dictionary<String,String>> TraeDatos2 = null;
	public static ArrayList<Dictionary<String,String>> Splash = null;
	public int EVEIDR;
	public TextView txtbusqueda;
	String busqueda = "";
	boolean inicial = true;
	

	public void voidFinish(View V) {
		finish();
	}

	public void abrirMenuLateral(View V) {
		intent = new Intent(Mensajes.this, MenuLateral.class);
		startActivity(intent);
	}

	@Override
	public void onBackPressed() {
	}
	
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_listview_sfv);
		
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		TextView Titulo = (TextView) this.findViewById(id.tv_listView_Titulo);
		Titulo.setText(R.string.st_centro_de_mensajes);
		EVEIDR = Utilities.EVE_IDR;

		EditText txtbusc = (EditText) this.findViewById(id.et_buscar_buscar);
		txtbusc.setOnEditorActionListener(new OnEditorActionListener() {
		    @Override
		    public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
		    	if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
		    		InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    		in.hideSoftInputFromWindow(v.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
			        buscar();
			        return true;
		        }
		        return false;
		    }
		});
		
		CargarContenido();	
	}
	
	private void CargarContenido() {
		// TODO Auto-generated method stub
		new AsyncContenido().execute("");
	}
	
	private class AsyncContenido extends AsyncTask<String, String, String>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(Mensajes.this, "",getString(R.string.st_cargando_));
		}

		@Override
		protected String doInBackground(String... params) {
			String strBusqueda = ((EditText) Mensajes.this.findViewById(id.et_buscar_buscar)).getText().toString().trim();
			busqueda = strBusqueda;
			
			String qry = "";
		    if (strBusqueda.length()>0) {
				qry ="select * from push where eve_idr=" + EVEIDR + 
						" and upper(push_text) like upper('%" + busqueda + "%') " +
						" order by push_fecha,push_idr,eve_idr";		    	
		    }else{
				qry ="select * from push where eve_idr=" + EVEIDR + " order by push_fecha,push_idr,eve_idr";		    	
		    }
			TraeDatos2 = Utilities.qry2(getApplicationContext(),qry);
			
			if(inicial){
				qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre = 'SPLASH EXPOSITORES' ORDER BY b.ban_nombre";
				Splash = Utilities.qry2(getApplicationContext(), qry);				
			}
			
			return null;
			
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			//acomodo encabezados
			TraeDatos = new ArrayList<Dictionary<String,String>>();
			Dictionary<String, String> dic = null;
			String encabezado = "";
		    for (int i=0; i<TraeDatos2.size(); i++) {
		    	String fecha = TraeDatos2.get(i).get("push_fecha").toString().substring(0,10);
		    	if(!encabezado.equals(fecha)){
		    		encabezado = fecha;
		    		dic = new Hashtable<String, String>();
				    dic.put("Header", encabezado);
				    TraeDatos.add(dic);
		    	}
		    	TraeDatos.add(TraeDatos2.get(i));
		    }
		    
		    progressDialog.dismiss();
		    
		    if(inicial){
		    	inicial = false;
		    	if(Splash.size()>0){
			    	dic = Splash.get(0);
			    	String strPoster = dic.get("ban_url").toString();
				    String strTimer = dic.get("ban_timer").toString();
				    String strPatrocinador = dic.get("pat_idr").toString();
				    if (strPoster.equals("null")) {
				        strPoster = "";
				    }
				    if(strPoster.length()>0){
						intent = new Intent(Mensajes.this, Splash2.class);
						Bundle bund = new Bundle();
						bund.putString("PUT_IMG",strPoster);
						bund.putString("PUT_PAT",strPatrocinador);
						bund.putString("PUT_TIME",strTimer);
						intent.putExtras(bund);
						startActivity(intent);
				    }
			    }
		    }
			
			Resources res = getResources();
			ListView listView = (ListView) findViewById(id.list);
			MensajesArrayAdapter adapter = new MensajesArrayAdapter(Mensajes.this, TraeDatos, res.getString(R.string.QRY_SERVLET));
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					muestra_detalle(position);
				}
			});
		}
	}

	public void borrar(View v){
		EditText txtbusc = (EditText) findViewById(id.et_buscar_buscar);
		txtbusc.setText("");
		buscar();
	}
	
	private void  muestra_detalle(int x){
		String cadena = TraeDatos.get(x).get("push_idr").toString();
		if(cadena != null){
			intent = new Intent(this, MensajesDetalle.class);
			Bundle bund = new Bundle();
			bund.putString("idmsg",cadena);
			intent.putExtras(bund);
			startActivity(intent);	
		}
	}

	public void fTodos(View v){
		ImageButton btnf = (ImageButton) findViewById(R.id.iv_btn_favoritos);
		ImageButton btnt = (ImageButton) findViewById(R.id.iv_btn_todos);
		if (btnt.getTag() == "0"){
			btnt.setImageResource(R.drawable.lst_btn_todos_act);	
			btnt.setTag("1");
			btnf.setImageResource(R.drawable.lst_btn_favoritos_des);
			btnf.setTag("0");
		}else{
			btnt.setImageResource(R.drawable.lst_btn_todos_des);
			btnt.setTag("0");
			btnf.setImageResource(R.drawable.lst_btn_favoritos_act);	
			btnf.setTag("1");
		}
	}
	
	public void fFavoritos(View v){
		ImageButton btnf = (ImageButton) findViewById(R.id.iv_btn_favoritos);
		ImageButton btnt = (ImageButton) findViewById(R.id.iv_btn_todos);
		if (btnf.getTag() == "0"){
			btnf.setImageResource(R.drawable.lst_btn_favoritos_act);	
			btnf.setTag("1");
			btnt.setImageResource(R.drawable.lst_btn_todos_des);
			btnt.setTag("0");
		}else{
			btnf.setImageResource(R.drawable.lst_btn_favoritos_des);
			btnf.setTag("0");
			btnt.setImageResource(R.drawable.lst_btn_todos_act);	
			btnt.setTag("1");
		}
	}
	
	public void detalle(View v){
		intent = new Intent(this, MensajesDetalle.class);
		startActivity(intent);
	}
	
	public void buscar(){
		String strBusqueda = ((EditText) findViewById(id.et_buscar_buscar)).getText().toString().trim();
		if(!strBusqueda.equals(busqueda)){
			CargarContenido();
		}
	}
	
	public void voidbusqueda(View v){
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		buscar();
		//CargarContenido();
	}
	
}
